const Service = require("egg").Service;
const { QueryTypes, Op } = require("sequelize");
const fs = require("fs");

class Commodity extends Service {
  // 根据名称查询商品
  async queryCommodityByName() {
    let name = this.ctx.query.name;
    console.log(name);
    try {
      let Commodity = await this.app.model.Commodity.findAll({
        where: { title: { [Op.like]: `%${name}%` } }
      });

      if (!Commodity) return { msg: "查询失败" };

      return Commodity;
    } catch (e) {
      console.log(e);
    }
  }

  // 查询商品列表
  async getCommodityList() {
    let Commoditytype = await this.app.model.Commodity.findAll();

    return Commoditytype;
  }

  // 添加商品
  async addCommodity() {
    try {
      let { title, desc, price, image, type_id, flower_language } =
        this.ctx.request.body;
      console.log(image);
      
      let obj = {
        title,
        desc,
        price,
        image,
        type_id,
        flower_language
      };

      let res = await this.app.model.Commodity.create(obj);

      if (!res)
        return {
          msg: "添加失败"
        };

      return {
        msg: "添加成功"
      };
    } catch (e) {
      console.log(e);
      return {
        msg: "只能添加三张图片"
      };
    }
  }

  // 修改商品名称
  async updateCommodity() {
    let id = this.ctx.params.id;
    console.log(id);
    let { title, desc, price, image, flower_language, type_id } =
      this.ctx.request.body;
    let obj = {
      title,
      desc,
      price,
      image,
      flower_language,
      type_id
    };

    let res = await this.app.model.Commodity.update(obj, {
      where: {
        id
      }
    });

    if (!res) return { msg: "修改失败" };

    return {
      msg: "修改成功"
    };
  }

  // 删除商品
  async deleteCommodity() {
    let id = this.ctx.params.id;

    let res = await this.app.model.Commodity.destroy({ where: { id } });

    let imgUrlObj = this.ctx.request.body;

    if (!res) return { msg: "删除失败" };

    // 循环删除商品的在文件夹图片
    imgUrlObj.forEach(item => {
      fs.unlinkSync("app" + item);
    });

    return {
      msg: "删除成功"
    };
  }

  // 根据id查询分类mign;
  async queryTypeNameById() {
    let url = this.ctx.request.url;

    let id = url.match(/=(\S*)/)[1];

    console.log(id);

    let Commoditytype = await this.app.model.Commoditytype.findAll({
      where: {
        id
      }
    });

    return Commoditytype;
  }

  // 根据分类id查询商品
  async queryProductsByTypeId() {
    // let type_id = this.ctx.request.body.type_id;

    let url = this.ctx.request.url;

    let type_id = url.match(/=(\S*)/)[1];

    let res = await this.app.model.Commodity.findAll({
      where: {
        type_id
      }
    });

    if (!res) return { msg: "查询失败" };

    return res;
  }
}

module.exports = Commodity;
